package com.ps.camera;

import java.io.File;

import org.apache.log4j.Logger;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Menu;
import android.widget.FrameLayout;

public class CameraActivity extends Activity {
	
	Logger log = Logger.getLogger(CameraActivity.class);
	private Camera mCamera;
	private CameraPreview mPreview;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try
		{
			File storagePath = SLogger.getStoragePath();
			SLogger.loadLogConfigurator(storagePath);
			log.info("Camera Application Created");
			
			// Get number of Cameras
        	int cameraCount = 0;
        	Camera cam = null;
        	Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        	cameraCount = Camera.getNumberOfCameras();
        	log.info("Number of cameras: " + cameraCount);
		
			log.info("Trying to load OpenCV library");
			if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mOpenCVCallBack))
			{
				log.info("Cannot connect to OpenCV Manager");
			}
			
			// Create an instance of Camera
			mCamera = getCameraInstance();
		
			// Create our Preview view and set it as the content of our activity.
			mPreview = new CameraPreview(this, mCamera);
			FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
			preview.addView(mPreview);
			
			OpenCVPreview ocvPreview = (OpenCVPreview)findViewById(R.id.opencv_preview);
			mPreview.setHandler(ocvPreview.getCalculateHandler());
		}
		catch (Exception e)
		{
			log.error(e.getMessage());
//			log.error(SLogger.getStackTrace());
		}
		
		setContentView(R.layout.activity_camera_preview);
		
	}
	
	public static Camera getCameraInstance() {
		Camera c = null;

		try {
			c = Camera.open(); // attempt to get a Camera instance
		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
		}
		return c; // returns null if camera is unavailable
	}
	
	private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this)
	{
		@Override
		public void onManagerConnected(int status)
		{
			switch (status)
			{
				case LoaderCallbackInterface.SUCCESS:
				{
					log.info("OpenCV loaded successfully");
					// Create and set View
				} break;
				case LoaderCallbackInterface.INIT_FAILED:
				{
					log.info("OpenCV loading failed");
				} break;
				default:
				{
					super.onManagerConnected(status);
				} break;
			}
		}
	};
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_camera, menu);
        return true;
    }
}
